import { logger } from '$common';
import { Storage } from '$infra';
import { AgentState } from './state';
import { storageCLI } from '$infra/storage/storage-cli';
import { agentConfig } from '../config';
import { RunningState } from './runningState';
import { buildAbilities, registerToGateway } from '../agentService';
export class RegisteringState extends AgentState {

  private static _instance: RegisteringState;

  public static get Instance() {
    if (!this._instance) {
      this._instance = new RegisteringState();
    }
    return this._instance;
  }

  private constructor() { super('registering'); }

  async establishConnection() { this.warnJump(); }
  async onSimulationRequest() { this.warnJump(); }
  async registerAbilities() {

    const agentAbilities = buildAbilities();
    const registratioResponse = await registerToGateway(agentAbilities);

    logger.debug(`✅ gateway response: ${JSON.stringify(registratioResponse)}`);

    if (registratioResponse.success) {
      logger.debug('🎃 register sucess.');

      Storage.initialize(registratioResponse.response.storage);

      if (agentConfig.storageCLIEnable) {
        await storageCLI.initialize(registratioResponse.response.storage);
      }

      this.context.transitionTo(RunningState.Instance);
      this.context.onSimulationRequest();
    } else {
      throw new Error(`❌ register failed, gateway responese data: ${JSON.stringify(registratioResponse)}`);
    }
  }
}